import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class Solution1019 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public int[] nextLargerNodes(ListNode head) {
        List<Integer> list=new ArrayList<>();
        while (head!=null){
            list.add(head.val);
            head=head.next;
        }
        int[] ans=new int[list.size()];
        Stack<Integer> stack=new Stack<>();
        for (int i=list.size()-1;i>=0;i--){
            while (!stack.isEmpty() && list.get(i)>=stack.peek()){
                stack.pop();
            }
            ans[i]=stack.isEmpty()?0:stack.peek();
            stack.push(list.get(i));
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution1019().nextLargerNodes(new ListNode(2, new ListNode(7, new ListNode(4, new ListNode(3, new ListNode(5))))))));
    }
}
